<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<el-row :gutter="20">
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item
							ref="Entity_ShiftId_FormItem"
							prop="Entity.ShiftId"
							label="Shift"
							:rules="[{ required: true, message: 'Shift为必填项', trigger: 'blur' }]"
						>
							<el-select v-model="stateData.vmModel.Entity.ShiftId" clearable class="width100">
								<el-option v-for="item in stateData.AllSysAttendanceShifts" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
							></el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item
							ref="Entity_GroupId_FormItem"
							prop="Entity.GroupId"
							label="Group"
							:rules="[{ required: true, message: 'Group为必填项', trigger: 'blur' }]"
						>
							<el-select v-model="stateData.vmModel.Entity.GroupId" clearable class="width100">
								<el-option v-for="item in stateData.AllSysAttendanceShiftGroups" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
							></el-select>
						</el-form-item>
					</el-col>
				</el-row>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>基本信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Tag_FormItem" prop="Entity.Tag">
								<template #label>
									<WtmLabelTooltip label="标签" tooltip="类型标签（A/B/C）" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.Tag" clearable class="width100">
									<el-option key="A" value="A" label="A"></el-option>
									<el-option key="B" value="B" label="B"></el-option>
									<el-option key="C" value="C" label="C"></el-option>
									<el-option key="D" value="D" label="D"></el-option
								></el-select>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<!--suppress JSAnnotator -->
<script setup lang="ts" name="message._system.common.vm.add;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, ComponentInternalInstance } from 'vue';
import { SysAttendanceShiftAndGroupApi as api } from '/@/views/hr/sysattendanceshiftandgroup/api';
import other from '/@/utils/other';
import { ISysAttendanceShiftAndGroupVm } from '/@/views/hr/sysattendanceshiftandgroup/api/interface';
import { IViewModel } from '/@/types/common';

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	CLOSE: '关闭',
} as const;
const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const hasSavedOnce = ref(false);
const stateData = reactive<IViewModel<ISysAttendanceShiftAndGroupVm>>({
	vmModel: {
		Entity: {
			ShiftId: null,
			GroupId: null,
			Tag: null,
		},
		ActionName: null,
		IsMyApprove: null,
	},
	AllSysAttendanceShifts: [],
	AllSysAttendanceShiftGroups: [],
});

const hasEntityId = computed(() => {
	const entity = stateData.vmModel.Entity as any;
	return !!(entity && entity.ID);
});
const handleApiResponse = (response: any) => {
	ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
	emit('refresh');
	loading.value = false;
	closeDialog();
};

const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

const handleApiRequest = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			beforeSubmit();
			apiCall()
				.then((response: any) => handleApiResponse(response))
				.catch(handleError);
		}
	});
};
// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSave = () => {
	handleApiRequest(
		() => {
			// 创建一个深拷贝，确保新增时不发送无效的 ID 字段
			const submitData = JSON.parse(JSON.stringify(stateData.vmModel));
			if (!submitData.Entity.ID) {
				// 如果没有有效的 ID，删除该字段
				delete submitData.Entity.ID;
			}
			return api().add(submitData);
		},
		() => {},
		false
	);
};

// 加载选择列表数据
const loadData = async () => {
	await Promise.allSettled([
		other.getSelectList('/api/SysAttendanceShiftAndGroup/GetSysAttendanceShifts', [], false).then((x) => (stateData.AllSysAttendanceShifts = x)),
		other
			.getSelectList('/api/SysAttendanceShiftAndGroup/GetSysAttendanceShiftGroups', [], false)
			.then((x) => (stateData.AllSysAttendanceShiftGroups = x)),
	]);
};

const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
		hasSavedOnce.value = true;
	}
};
// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 并行加载选择列表数据
		await loadData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SUBMIT,
			type: 'primary',
			onClick: onSave,
			visible: true,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];
	emit('updateHeaderButtons', headerButtons);
};
</script>
